/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.zprofilefrontend.model;

import com.vng.zing.zprofilefrontend.common.Util;
import com.vng.zing.calc.thrift.Profile;
import com.vng.zing.calc.thrift.ProfilePage;
import com.vng.zing.calc.thrift.ProfileSession;
import com.vng.zing.calc.thrift.ROLE;
import com.vng.zing.calc.thrift.STATUS;
import com.vng.zing.logger.ZLogger;
import com.vng.zing.stats.Profiler;
import com.vng.zing.stats.ThreadProfiler;
import com.vng.zing.stats.monitor.common.TemplateManager;
import static com.vng.zing.zprofilefrontend.model.BaseModel.checkLogIn;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author namhh
 */
public class ProfileListModel extends BaseModel {

    private static final Logger _Logger = ZLogger.getLogger(ProfileListModel.class);
    public static final ProfileListModel Instance = new ProfileListModel();
    public static int OFFSET = 12;

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        ThreadProfiler profiler = Profiler.getThreadProfiler();

        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = null;
        try {
            out = resp.getWriter();
            profiler.push(this.getClass(), "output");
            ProfileSession profileSession = checkLogIn(req);
            Profile profileFromSession = getClientWithCache().getaLoad(profileSession.getId());
            if (null != profileFromSession && (profileFromSession.getRole().equals(ROLE.ADMIN))) {

                if (null != req.getParameter("page") && Util.isShort(req.getParameter("page"))) {
                    short page = Short.parseShort(req.getParameter("page"));
                    TemplateDataDictionary dic = TemplateDictionary.create();
                    ProfilePage profiles = getClient().getAllProfile((page - 1) * OFFSET, OFFSET);
                    if (null != profiles) {
                        int cnt = (page - 1) * OFFSET + 1;
                        for (Map.Entry<Integer, Profile> map : profiles.getProfileMap().entrySet()) {
                            Profile profile = map.getValue();
                            TemplateDataDictionary profileSlice = dic.addSection("SLICE_PROFILE");
                            profileSlice.setVariable("NUMBER", String.format("%s", cnt));
                            profileSlice.setVariable("PROFILE_ID", String.format("%s", profile.getId()));
                            profileSlice.setVariable("USERNAME", profile.getUsername());
                            profileSlice.setVariable("GENDER", profile.getGender().name());
                            profileSlice.setVariable("DISPLAY_NAME", profile.getDisplayName());
                            profileSlice.setVariable("ROLE", profile.getRole().name());
                            profileSlice.setVariable("DATE_OF_BIRTH", Util.toDate(profile.getDateOfBirth()));
                            if (STATUS.ACTIVE.equals(profile.getStatus())) {
                                profileSlice.setVariable("ACTIVE_CHECKED", "checked");
                            } else {
                                profileSlice.setVariable("DEACTIVE_CHECKED", "checked");
                            }
                            cnt++;
                        }

                        Template home = TemplateManager.getTemplate("profile-pagging");
                        out.println(home.renderToString(dic));
                    }
                } else {
                    TemplateDataDictionary dic = TemplateDictionary.create();
                    setHeaderFooter("ZProfile -Profile List", dic, profileFromSession);
                    ProfilePage profiles = getClient().getAllProfile(0, OFFSET);
                    if (null != profiles) {
                        int totalPage = (int) Math.ceil(profiles.getTotal() * 1.0 / OFFSET);
                        dic.setVariable("TOTAL_PAGE", String.format("%s", totalPage));
                        dic.setVariable("OFFSET", String.format("%s", OFFSET));
                        int cnt = 1;
                        for (Map.Entry<Integer, Profile> map : profiles.getProfileMap().entrySet()) {
                            Profile profile = map.getValue();
                            TemplateDataDictionary profileSlice = dic.addSection("SLICE_PROFILE");
                            profileSlice.setVariable("NUMBER", String.format("%s", cnt));
                            profileSlice.setVariable("PROFILE_ID", String.format("%s", profile.getId()));
                            profileSlice.setVariable("USERNAME", profile.getUsername());
                            profileSlice.setVariable("GENDER", profile.getGender().name());
                            profileSlice.setVariable("DISPLAY_NAME", profile.getDisplayName());
                            profileSlice.setVariable("ROLE", profile.getRole().name());
                            profileSlice.setVariable("DATE_OF_BIRTH", Util.toDate(profile.getDateOfBirth()));
                            if (STATUS.ACTIVE.equals(profile.getStatus())) {
                                profileSlice.setVariable("ACTIVE_CHECKED", "checked");
                            } else {
                                profileSlice.setVariable("DEACTIVE_CHECKED", "checked");
                            }
                            cnt++;
                        }

                        Template home = TemplateManager.getTemplate("list");
                        out.println(home.renderToString(dic));
                    }
                    /////////////
                }
                ////////////
            } else {
                resp.sendRedirect("/login");
            }

            profiler.pop(this.getClass(), "output");
        } catch (Exception ex) {
            _Logger.error(null, ex);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
